import { useState } from "react";
import { Navigator, View } from "@tarojs/components";
import Taro, { useDidShow, useReachBottom } from "@tarojs/taro";
import { useCreation, useSetState, useUpdateEffect } from "ahooks";

import Tabs from "./components/Tabs";
import Page from "@/components/common/Page";
import TabsTag from "@/components/app/TabsTag";
import ByAvatar from "@/components/ui/ByAvatar";
import ListView from "@/components/app/ListView";
import TodoCard from "@/components/app/TodoCard";
import PageHeader from "@/components/common/PageHeader";
import PopupPlanExecution from "./components/PopupPlanExecution";

import useAppStore from "@/store";
import useList from "@/hooks/useList";
import ApiWorkflow from "@/api/workflow";

import { TaskItem } from "@/types/global";

const defaultTypeList = [
  { label: "全部", value: 0 },
  { label: "拟定", value: 1 },
  { label: "执行", value: 2 },
  { label: "选材", value: 3 },
  { label: "工费", value: 4 },
  { label: "派工", value: 5 },
  // { label: "项目结算", value: 7 },
];

export default function Index() {
  const userInfo = useAppStore((state) => state.userInfo);

  const [search, setSearch] = useSetState<{
    // 0.待办， 1.已办， 2.抄送 3.发起
    status: number;
    // 待办事项， 1:计划拟定，2:计划执行，3:主材选材，4:工费申请， 5: 派工
    itemType: number;
  }>({
    status: 0,
    itemType: 0,
  });

  // 获取列表数据
  const { loading, list, originData, nextPage, resetToFirst } =
    useList<TaskItem>(ApiWorkflow.todos, {
      manual: true,
      showLoading: true,
      defaultParams: [search],
    });

  // 标签Tabs列表
  const typeList = useCreation(() => {
    const list = [...defaultTypeList];
    if (originData) {
      const total = originData.total;

      if (search.itemType === 0 && search.status === 0) {
        list[0]["label"] = `全部(${total})`;
        const totalText = total > 99 ? "99+" : total;
        Taro.setTabBarBadge({ index: 0, text: totalText + "" });
      }
    }
    return list;
  }, [originData]);

  useUpdateEffect(() => {
    resetToFirst(search);
  }, [search]);

  useDidShow(() => resetToFirst(search))
  useReachBottom(() => nextPage());

  const [selected, setSelected] = useState<TaskItem>();
  return (
    <>
      <Page
        slotHeader={
          <View className="bg-page">
            <PageHeader showBack={false}>
              <Navigator hover-class="none" url="/pages/mine/index">
                <ByAvatar
                  src={userInfo?.avatar}
                  alt={userInfo?.user_name}
                  className="bg-primary text-white"
                />
              </Navigator>
            </PageHeader>

            <Tabs
              initialActive={search.status}
              onChange={(status) => setSearch({ status })}
            />

            {search.status === 0 && (
              <View className="mt-3 px-4">
                <TabsTag
                  items={typeList}
                  active={search.itemType}
                  onChange={(itemType) => setSearch({ itemType })}
                />
              </View>
            )}
          </View>
        }
      >
        <View className="p-4">
          <ListView loading={loading} isEmpty={list.length == 0}>
            {list.map((item) => (
              <TodoCard
                key={item.id}
                source={item}
                onClick={() => setSelected(item)}
              />
            ))}
          </ListView>
        </View>
      </Page>

      {selected?.itemType === 2 && (
        <PopupPlanExecution
          intentCustomerId={selected.intentCustomerId}
          onCancel={() => setSelected(undefined)}
        />
      )}
    </>
  );
}
